package cn.liutao.upload.api;

import cn.hutool.core.net.multipart.MultipartFormData;
import cn.hutool.core.net.multipart.UploadFile;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.liutao.common.enums.CommonEnum;
import cn.liutao.common.exception.OrderException;
import cn.liutao.common.utils.ServletUtils;
import cn.liutao.dish.entity.po.DiningTable;
import cn.liutao.dish.service.DiningTableService;
import com.mybatisflex.core.row.Db;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

/**
 * @author: liutao
 * @description: 餐桌二维码api
 * @date: 2023/11/21 22:11
 */
@WebServlet("/upload/qrCode")
@Slf4j
public class QrCodeCreateServlet extends UploadServlet {
    private String directory = CommonEnum.FILE_UPLOAD_DIRECTORY.getValue();
    private String path = CommonEnum.QRCODE_UPLOAD_DIRECTORY.getValue();

    private DiningTableService diningTableService;

    @Override
    public void init() throws ServletException {
        diningTableService = DiningTableService.getInstance();
        super.init();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) {
        //获取文件参数
        if (!ServletUtil.isMultipart(req)) {
            throw new OrderException("请使用文件上传");
        }
        MultipartFormData multipart = ServletUtil.getMultipart(req);
        UploadFile file = multipart.getFile("file");
        String tableId = multipart.getParam("tableId");
        if (StrUtil.isBlank(tableId)){
            throw new OrderException("请选择餐桌");
        }
        String content = multipart.getParam("content");
        if (StrUtil.isBlank(content)){
            throw new OrderException("二维码内容不能为空");
        }
        Db.tx(()->{
            DiningTable diningTable = diningTableService.selectById(Long.valueOf(tableId));
            if (ObjectUtil.isNull(diningTable)){
                throw new OrderException("选择的餐桌不存在");
            }
            //生成二维码
            File qrFile = uploadService.generateQrCode(file,tableId,content);
            //上传二维码文件
            url = uploadService.upload(qrFile, path);
            //将文件地址信息保存到餐桌表
            diningTable.setImg(url);
            diningTableService.updateById(diningTable);
            return true;
        });
        ServletUtils.ok(resp,url,"上传成功");
        log.info("文件上传成功,URL:{}",url);
    }
}
